package com.kinggm.controller;

import com.kinggm.util.RedisLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test")
public class RedisLockDemoController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "simpleRedisLock")
    private RedisLock simpleRedisLock;


    @Resource(name = "reentrantRedisLock")
    private RedisLock reentrantRedisLock;


    /**
     * 测试 SimpleRedisLock
     */
    @GetMapping("/aa")
    public String testA() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        boolean lock = simpleRedisLock.tryLock(stringRedisTemplate, "testA", uuid, 25);
        if (lock) {
            try {
                System.out.println("获取锁成功！");
                TimeUnit.SECONDS.sleep(20);
                return "aa成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                simpleRedisLock.releaseLock(stringRedisTemplate, "testA", uuid);
            }
        }
        return "获取锁失败";

    }


    /**
     * 测试 ReentrantRedisLock
     */
    @GetMapping("/bb")
    public String testB() {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        boolean lock = reentrantRedisLock.tryLock(stringRedisTemplate, "testA", uuid, 25);
        if (lock) {
            try {
                System.out.println("获取锁成功！");
                TimeUnit.SECONDS.sleep(5);
                // 测试锁 重入
                bb(reentrantRedisLock,uuid);
                return "aa成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 记得使用 带释放时间的方法
                reentrantRedisLock.releaseLock(stringRedisTemplate, "testA", uuid,25);
            }
        }
        return "获取锁失败";

    }


    private void bb(RedisLock lock, String uuid) {
        boolean b = lock.tryLock(stringRedisTemplate, "testA", uuid, 25);
        try {
            if (b) {
                System.out.println("锁重入成功");
                TimeUnit.SECONDS.sleep(5);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 最后一个参数 是锁自动释放时间
            lock.releaseLock(stringRedisTemplate, "testA", uuid,25);
        }
    }


}
